/**
 * @Title: inputTips_directive.js
 * @Description: 输入提示
 * Copyright: Copyright (c) 2014 
 * Company:中国平安
 *
 * @Project HIMS-FWA
 * @author QIANDUO875
 * @date 2014年9月30日 下午1:26:26
 * @version V1.0
 */
;
(function(){
	'use strict';
	
	
	var app = angular.module('fwa.directives');
	
	app.directive('fwaInputTips',['$compile','$parse',function($compile,$parse){
		
		var tmpl = '\
			<ul class="input-select-ul">\
				<li ng-repeat="data in items" ng-bind="data.text || data" ng-click="onSelectItem(data)"></li>\
			</ul>';
		
		function compile($telem, $attrs, $transclude) {
			return function($scope, $elem, $attrs, $ctrls){
				var ul = $compile(tmpl)($scope);
				var modelFn = $parse($attrs.ngModel);
				var modelAssignFn = modelFn.assign;
				var minInputCount = $attrs.minWord || 2;
				var inputChange = $scope.$parent.$eval($attrs.inputChange);
				var model = null;
				var preventChangeEvent = false;
				var selectEventFn = $parse($attrs.itemSelect);
				var init = true;
				
				$('body').append(ul);
				ul.hide();
				
				$scope.$parent.$watch($attrs.list, function(v){
					$scope.items = v;
				});
				
				$scope.onSelectItem = function(data) {
					model = data;
					$ctrls.$setViewValue(model.text || model);
					$elem.unbind('keyup' , change);
					$ctrls.$render();
					$elem.on('keyup',change);
					modelAssignFn($scope.$parent, model);
					$ctrls.$modelValue = model;
					if(selectEventFn) {
						selectEventFn($scope.$parent,{$item:data});
					}
				}
				
				function change() {
					var typeIn = $elem.val();
					if(inputChange && typeIn != null && typeIn.length>=minInputCount) {
						inputChange(typeIn);
					}
				}
				
				$elem.on('keyup' , change);
				
				$elem.on('focus',function(e){
					var p = $elem.offset();
					ul.css({
						top:0,
						left:0,
						width:$elem.width()+14
					});
					ul.offset({
						top:p.top + $elem.height() + 10,
						left:p.left
					});
					
					change();
					ul.show(200, function(){
						
					});
				});
				
				$elem.on('blur', function(){
					ul.hide(200, function(){
						if(!$elem.val() || $.trim($elem.val().length) ==0) {
							model = null;
						}
						if(!model) {
							var wModel = modelFn($scope.$parent);
							if(!wModel) {
								$ctrls.$setViewValue('');
							} else {
								$ctrls.$setViewValue(wModel.text || wModel);
							}
						} else {
							$ctrls.$setViewValue(model.text || model);
						}
						$elem.unbind('keyup' , change);
						$ctrls.$render();
						$elem.on('keyup',change);
					});
				});
			}
		}
		
		return {
			restrict:'E',
			template:'<input >',
			replace:true,
			require:'?ngModel',
			scope:true,
			compile:compile
		};
	}]);
	
	
})();